1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.collect;
18  
19  import static com.google.common.collect.CollectPreconditions.checkNonnegative;
20  
21  import com.google.common.annotations.GwtCompatible;
22  import com.google.common.annotations.GwtIncompatible;
23  import com.google.common.annotations.VisibleForTesting;
24  
25  import java.io.IOException;
26  import java.io.ObjectInputStream;
27  import java.io.ObjectOutputStream;
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.HashMap;
31  import java.util.List;
32  import java.util.Map;
33  
34  /**
35   * Implementation of {@code Multimap} that uses an {@code ArrayList} to store
36   * the values for a given key. A {@link HashMap} associates each key with an
37   * {@link ArrayList} of values.
38   *
39   * <p>When iterating through the collections supplied by this class, the
40   * ordering of values for a given key agrees with the order in which the values
41   * were added.
42   *
43   * <p>This multimap allows duplicate key-value pairs. After adding a new
44   * key-value pair equal to an existing key-value pair, the {@code
45   * ArrayListMultimap} will contain entries for both the new value and the old
46   * value.
47   *
48   * <p>Keys and values may be null. All optional multimap methods are supported,
49   * and all returned views are modifiable.
50   *
51   * <p>The lists returned by {@link #get}, {@link #removeAll}, and {@link
52   * #replaceValues} all implement {@link java.util.RandomAccess}.
53   *
54   * <p>This class is not threadsafe when any concurrent operations update the
55   * multimap. Concurrent read operations will work correctly. To allow concurrent
56   * update operations, wrap your multimap with a call to {@link
57   * Multimaps#synchronizedListMultimap}.
58   * 
59   * <p>See the Guava User Guide article on <a href=
60   * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap">
61   * {@code Multimap}</a>.
62   *
63   * @author Jared Levy
64   * @since 2.0 (imported from Google Collections Library)
65   */
66  @GwtCompatible(serializable = true, emulated = true)
67  public final class ArrayListMultimap<K, V> extends AbstractListMultimap<K, V> {
68    // Default from ArrayList
69    private static final int DEFAULT_VALUES_PER_KEY = 3;
70  
71    @VisibleForTesting transient int expectedValuesPerKey;
72  
73    /**
74     * Creates a new, empty {@code ArrayListMultimap} with the default initial
75     * capacities.
76     */
77    public static <K, V> ArrayListMultimap<K, V> create() {
78      return new ArrayListMultimap<K, V>();
79    }
80  
81    /**
82     * Constructs an empty {@code ArrayListMultimap} with enough capacity to hold
83     * the specified numbers of keys and values without resizing.
84     *
85     * @param expectedKeys the expected number of distinct keys
86     * @param expectedValuesPerKey the expected average number of values per key
87     * @throws IllegalArgumentException if {@code expectedKeys} or {@code
88     *      expectedValuesPerKey} is negative
89     */
90    public static <K, V> ArrayListMultimap<K, V> create(
91        int expectedKeys, int expectedValuesPerKey) {
92      return new ArrayListMultimap<K, V>(expectedKeys, expectedValuesPerKey);
93    }
94  
95    /**
96     * Constructs an {@code ArrayListMultimap} with the same mappings as the
97     * specified multimap.
98     *
99     * @param multimap the multimap whose contents are copied to this multimap
100    */
101   public static <K, V> ArrayListMultimap<K, V> create(
102       Multimap<? extends K, ? extends V> multimap) {
103     return new ArrayListMultimap<K, V>(multimap);
104   }
105 
106   private ArrayListMultimap() {
107     super(new HashMap<K, Collection<V>>());
108     expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
109   }
110 
111   private ArrayListMultimap(int expectedKeys, int expectedValuesPerKey) {
112     super(Maps.<K, Collection<V>>newHashMapWithExpectedSize(expectedKeys));
113     checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey");
114     this.expectedValuesPerKey = expectedValuesPerKey;
115   }
116 
117   private ArrayListMultimap(Multimap<? extends K, ? extends V> multimap) {
118     this(multimap.keySet().size(),
119         (multimap instanceof ArrayListMultimap) ?
120             ((ArrayListMultimap<?, ?>) multimap).expectedValuesPerKey :
121             DEFAULT_VALUES_PER_KEY);
122     putAll(multimap);
123   }
124 
125   /**
126    * Creates a new, empty {@code ArrayList} to hold the collection of values for
127    * an arbitrary key.
128    */
129   @Override List<V> createCollection() {
130     return new ArrayList<V>(expectedValuesPerKey);
131   }
132 
133   /**
134    * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
135    */
136   public void trimToSize() {
137     for (Collection<V> collection : backingMap().values()) {
138       ArrayList<V> arrayList = (ArrayList<V>) collection;
139       arrayList.trimToSize();
140     }
141   }
142 
143   /**
144    * @serialData expectedValuesPerKey, number of distinct keys, and then for
145    *     each distinct key: the key, number of values for that key, and the
146    *     key's values
147    */
148   @GwtIncompatible("java.io.ObjectOutputStream")
149   private void writeObject(ObjectOutputStream stream) throws IOException {
150     stream.defaultWriteObject();
151     stream.writeInt(expectedValuesPerKey);
152     Serialization.writeMultimap(this, stream);
153   }
154 
155   @GwtIncompatible("java.io.ObjectOutputStream")
156   private void readObject(ObjectInputStream stream)
157       throws IOException, ClassNotFoundException {
158     stream.defaultReadObject();
159     expectedValuesPerKey = stream.readInt();
160     int distinctKeys = Serialization.readCount(stream);
161     Map<K, Collection<V>> map = Maps.newHashMapWithExpectedSize(distinctKeys);
162     setMap(map);
163     Serialization.populateMultimap(this, stream, distinctKeys);
164   }
165 
166   @GwtIncompatible("Not needed in emulated source.")
167   private static final long serialVersionUID = 0;
168 }